package client.ui.panel;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Logger;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

import client.ClientManager;
import client.EventBus;
import client.Handler;
import client.events.AddAppointment;
import client.events.PatientEdit;
import client.events.PatientSearch;
import client.events.ViewAppointments;
import client.events.ViewHistory;
import client.events.ViewHome;
import client.events.ViewInvoice;
import client.events.ViewPatientInvoice;
import client.events.ViewTR;
import client.io.ClientIO;
import domain.session.UserSession;
import domain.user.User;


public class TabbedDefault extends JPanel{
	


	/**
	 * @version 1.1 06/02/99
	 */
	
	private static CardLayout c;
	private static TabbedDefault td2;
	private static LoginPanel l;
	private static JFrame frame;
	private static HomePanel home=new HomePanel();
	private User user;
	private static PatientInvoicePanel inv;
	private static LoginPanel log;
	private static final Logger LOGGER = Logger.getLogger(ClientManager.class
			.getName());
	private static final String HOST = "localhost";
	public static UserSession SESSION = new UserSession(0, 0);
	private static final Integer PORT = 12345;
	//private PatientEdit pEdit;
	private static PatientPanel patient;
	private static ResultsPanel results;
	private static AppointmentPanel apt=new AppointmentPanel();
	private static TRPanel trp;
	private static HistoryPanel hist;
	private static DoctorInvoicePanel docIn;
	private static AddAppointmentPanel aap;
	private Integer iD;
	private static TabFocus tf;
	//=new TabFocus();
	public TabbedDefault(final PatientInvoicePanel inv, final HomePanel home , LoginPanel log,
			final PatientPanel patient, final ResultsPanel results, final AppointmentPanel apt, final TRPanel trp,
			final HistoryPanel hist,final DoctorInvoicePanel docIn,final AddAppointmentPanel aap ) {
	//public TabbedDefault(User user) {
		this.home=home;
		this.inv=inv;
		this.log=log;
		this.aap=aap;
		this.patient=patient;
		this.results=results;
		this.apt=apt;
		this.trp=trp;
		this.hist=hist;
		this.docIn=docIn;
		//home=new HomePanel();
		//this.user=user;
		tf=new TabFocus();
		addFocusListener(tf);

	   setLayout(new BorderLayout());
	   final MyMnemonics tabbedPane = new MyMnemonics();
	   String[] tabs = { "Home", "Patients", "Appointment", "Invoice", "Other" };
	   char[] ms = { 'H', 'P', 'A', 'I', 'F' };
	   int[] keys = { KeyEvent.VK_0, KeyEvent.VK_1, KeyEvent.VK_2,
	        KeyEvent.VK_3, KeyEvent.VK_4, };

	  // for (int i = 0; i < tabs.length; i++) {
	  //    tabbedPane.addTab(tabs[i], create+tabs[i]+Pane(tabs[i]));
	   //   tabbedPane.setMnemonicAt(i, ms[i]);
	      //tabbedPane.setMnemonicAt(i, keys[i]);
	   //}
	   
	   // outline for mnemonics
	   /**
	    *
	   tabbedPane.addTab(tabs[], createPane(tabs[]));
	   tabbedPane.setMnemonicAt(, ms[]);
	   tabbedPane.setMnemonicAt(, keys[]);
	   */
	   
	   
	   /*
	    * Hometab
	    */
	   tabbedPane.addTab(tabs[0], createHomePane(tabs[4]));
	   tabbedPane.setMnemonicAt(0, ms[0]);
	   tabbedPane.setMnemonicAt(0, keys[0]);
	   
	   
	   /*
	    * patient tab
	    */
	   
	   tabbedPane.addTab(tabs[1], createPatientPane(tabs[1]));
	   tabbedPane.setMnemonicAt(1, ms[1]);
	   tabbedPane.setMnemonicAt(1, keys[1]);
	   
	   /*
	    * appointment tab
	    */
	   tabbedPane.addTab(tabs[2], createAppointmentPane(tabs[2]));
	   tabbedPane.setMnemonicAt(2, ms[2]);
	   tabbedPane.setMnemonicAt(2, keys[2]);
	   
	   /*
	    * invoice tab
	    */
	   tabbedPane.addTab(tabs[3], createPatientInvoicePane(tabs[3]));
	   tabbedPane.setMnemonicAt(3, ms[3]);
	   tabbedPane.setMnemonicAt(3, keys[3]);
	   
	   tabbedPane.addTab(tabs[4], createHistoryPane(tabs[4]));
	   tabbedPane.setMnemonicAt(4, ms[4]);
	   tabbedPane.setMnemonicAt(4, keys[4]);
	   
	   
	   
	   
	   tabbedPane.add("Title",createTitlePane("title") );
	   tabbedPane.setMnemonicAt(5,'5');
	   
	   tabbedPane.setSelectedIndex(0);
	   add(tabbedPane, BorderLayout.CENTER);
	   
	   add(new BasicInfoPanel(), BorderLayout.WEST);
	   add(new TitlePanel(), BorderLayout.NORTH);
	   
	   
	   final CardLayout cardLayout = new CardLayout();
		final EventBus bus = EventBus.BUS;
		bus.addHandler(ViewHome.class, new Handler<ViewHome>() {
			public void handle(){
				
			}
			@Override
			public void handle(ViewHome event) {
				final Integer id = ClientManager.SESSION.getUserId();
				setClient(id);
				//frame.add(td2);
				//frame.setComponentZOrder(l, 0);
				home.updateUser(id);
				//dTab.getHome().updateUser(id);
				//frame.remove(0);
				//frame.validate();
				//frame.show();
				patient.updateUser(id);
				results.updateUser(id);
				apt.updateUser(id);
				trp.updateUser(id);
				hist.updateUser(id);
				home.addUser(id);
				inv.updateUser(id);
				docIn.updateUser(id);
				aap.updateUser(id);
				//l.setFocusable(false);
				tabbedPane.setSelectedIndex(0);
				//home.setFocusable(false);
				//home.setFocusable(true);
				//System.out.println("Yo");
				
				
				

				//patientInvoice.updateAppointment(null);
				//cardLayout.show(Home.getParent(), "Home");
				c.show(td2.getParent(), "Tabbed");
				//c.next(frame);

			}
			

		});
		bus.addHandler(PatientEdit.class, new Handler<PatientEdit>() {
			@Override
			public void handle(PatientEdit event) {
				//cardLayout.show(patient.getParent(), "PatientEdit");
				patient.addUser(event.patient);
				tabbedPane.setSelectedIndex(1);
			}
		});
		bus.addHandler(PatientSearch.class, new Handler<PatientSearch>() {
			@Override
			public void handle(PatientSearch event) {
				//cardLayout.show(results.getParent(),
					//	"PatientSearchResults");
				results.addResults(event.resultsList);
			}
		});
		bus.addHandler(ViewAppointments.class, new Handler<ViewAppointments>() {
			@Override
			public void handle(ViewAppointments event) {
				//cardLayout.show(apt.getParent(), "Appointments");
				apt.addAppointments(event.appointments, event.user);
			}
		});
		bus.addHandler(ViewTR.class, new Handler<ViewTR>() {
			@Override
			public void handle(ViewTR event) {
				//cardLayout.show(trp.getParent(), "TR");
				trp.addTreatmentRecord(event.record);
			}
		});
		bus.addHandler(ViewHistory.class, new Handler<ViewHistory>() {
			@Override
			public void handle(ViewHistory event) {
				//cardLayout.show(hist.getParent(), "History");
				hist.addPatient(event.patient);
				tabbedPane.setSelectedIndex(1);
			}
		});
		bus.addHandler(ViewPatientInvoice.class,
				new Handler<ViewPatientInvoice>() {
					@Override
					public void handle(ViewPatientInvoice event) {
						cardLayout.show(inv.getParent(),
								"PatientInvoice");
						inv.updateAppointment(event.appointment);
					}
				});
		bus.addHandler(ViewInvoice.class, new Handler<ViewInvoice>() {
			@Override
			public void handle(ViewInvoice event) {
				cardLayout.show(docIn.getParent(), "DoctorInvoice");
				docIn.updateDoctor(null);
				tabbedPane.setSelectedIndex(3);
			}
		});
		bus.addHandler(AddAppointment.class, new Handler<AddAppointment>() {
			@Override
			public void handle(AddAppointment event) {
				cardLayout.show(aap.getParent(), "AddAppointment");
				aap.addUser(event.user);
				tabbedPane.setSelectedIndex(2);
			}
		});
		
    
	
	
	
	}
	JPanel createTitlePane(final String s){
		JPanel pan=new JPanel();
		JLabel label=new JLabel("Info and Pics");
		pan.add(label);
		
		return pan;
	}

	JPanel createPane(final String s) {
	   //JButton abcButton = new JButton("Abc");
	   //abcButton.setMnemonic('A');
	   //JButton xyzButton = new JButton("Xyz");
	   //xyzButton.setMnemonic('X');

	   JPanel pan = new JPanel();
	   pan.add(new JLabel(s));
	   //pan.add(abcButton);
	   //pan.add(xyzButton);
	   return pan;
	} 
	JPanel createPatientPane(final String s) {
		   //patient=new PatientPanel();

		   //JPanel pan = new JPanel();
		   //pan.add(new JLabel(s));
		   return patient;
	}
	
	
	
	JPanel createAppointmentPane(final String s) {
		if(this.hasFocus()){
			apt.updateUser(iD);
		}
			
		System.out.println("Executed");

		   //apt = new AppointmentPanel();
		   //pan.add(new JLabel(s));
		   return apt;
	}
	JPanel createAddAppointmentPane(final String s){
		//aap=new AddAppointmentPanel();
		return aap;
	}
	JPanel createPatientInvoicePane(final String s) {
		inv=new PatientInvoicePanel();
		   //pan.add(new JLabel(s));
		   return inv;
	}
	JPanel createHomePane(final String s) {
		//home=new HomePanel();
		   //pan.add(new JLabel(s));
		   return home;
	}
	
	JPanel createHistoryPane(final String s){
		hist=new HistoryPanel();
		
		return hist;
	}
/**	public static void main(String[] args) {
	   JFrame frame = new JFrame("TabbedPane Test");
	   frame.addWindowListener(new WindowAdapter() {
	   public void windowClosing(WindowEvent e) {
	        System.exit(0);
	   }
	    });
	    PatientInvoicePanel in=new PatientInvoicePanel();
	    HomePanel ho=new HomePanel();
	    frame.getContentPane().add(new TabbedDefault(in, ho));
	    frame.setSize(700, 700);
	    frame.setVisible(true);
  }
  */
	
	public HomePanel getHome(){
		return home;
	}
	/**private void show(){
		final CardLayout cardLayout = new CardLayout();
		final EventBus bus = EventBus.BUS;
		bus.addHandler(ViewHome.class, new Handler<ViewHome>() {
			public void handle(){
				
			}
			@Override
			public void handle(ViewHome event) {
				final Integer id = ClientManager.SESSION.getUserId();
				home.updateUser(id);
				//dTab.getHome().updateUser(id);
				patient.updateUser(id);
				results.updateUser(id);
				apt.updateUser(id);
				trp.updateUser(id);
				hist.updateUser(id);
				home.addUser(id);
				inv.updateUser(id);
				docIn.updateUser(id);
				aap.updateUser(id);
				

				// patientInvoice.updateAppointment(null);
				//cardLayout.show(Home.getParent(), "Home");
				//cardLayout.show(dTab, "TabbedHome");

			}

		});
		bus.addHandler(PatientEdit.class, new Handler<PatientEdit>() {
			@Override
			public void handle(PatientEdit event) {
				cardLayout.show(patient.getParent(), "PatientEdit");
				patient.addUser(event.patient);
			}
		});
		bus.addHandler(PatientSearch.class, new Handler<PatientSearch>() {
			@Override
			public void handle(PatientSearch event) {
				cardLayout.show(results.getParent(),
						"PatientSearchResults");
				results.addResults(event.resultsList);
			}
		});
		bus.addHandler(ViewAppointments.class, new Handler<ViewAppointments>() {
			@Override
			public void handle(ViewAppointments event) {
				cardLayout.show(apt.getParent(), "Appointments");
				apt.addAppointments(event.appointments, event.user);
			}
		});
		bus.addHandler(ViewTR.class, new Handler<ViewTR>() {
			@Override
			public void handle(ViewTR event) {
				cardLayout.show(trp.getParent(), "TR");
				trp.addTreatmentRecord(event.record);
			}
		});
		bus.addHandler(ViewHistory.class, new Handler<ViewHistory>() {
			@Override
			public void handle(ViewHistory event) {
				cardLayout.show(hist.getParent(), "History");
				hist.addPatient(event.patient);
			}
		});
		bus.addHandler(ViewPatientInvoice.class,
				new Handler<ViewPatientInvoice>() {
					@Override
					public void handle(ViewPatientInvoice event) {
						cardLayout.show(inv.getParent(),
								"PatientInvoice");
						inv.updateAppointment(event.appointment);
					}
				});
		bus.addHandler(ViewInvoice.class, new Handler<ViewInvoice>() {
			@Override
			public void handle(ViewInvoice event) {
				cardLayout.show(docIn.getParent(), "DoctorInvoice");
				docIn.updateDoctor(null);
			}
		});
		bus.addHandler(AddAppointment.class, new Handler<AddAppointment>() {
			@Override
			public void handle(AddAppointment event) {
				cardLayout.show(aap.getParent(), "AddAppointment");
				aap.addUser(event.user);
			}
		});
		
	} */
	public static void main(String[] args){
		CardLayout cl=new CardLayout();
		PatientPanel pat =new PatientPanel();;
		ResultsPanel res=new ResultsPanel();;
		AppointmentPanel ap= new AppointmentPanel();
		TRPanel tr=new TRPanel();;
		HistoryPanel hi=new HistoryPanel();
		DoctorInvoicePanel docI=new DoctorInvoicePanel();
		AddAppointmentPanel aa=new AddAppointmentPanel();
		PatientInvoicePanel in=new PatientInvoicePanel();
		HomePanel hom=new HomePanel();
		LoginPanel lo=new LoginPanel(cl);
		
		
		final TabbedDefault td=new TabbedDefault(in, hom, lo, pat, res, ap, tr, hi, docI, aa);
		td2=td;
		c=new CardLayout();
		
		l=new LoginPanel(c);
		frame=new JFrame();
		frame.setLayout(c);
		frame.add(l, "Login");
		c.addLayoutComponent(l, "Login");
		frame.add(td2, "Tabbed");
		c.addLayoutComponent(td2,"Tabbed");
		
		//l.addFocusListener(tf);
		// variableUsage
		//td.show();
		td.connect();
		
		frame.addHierarchyListener(tf);
		frame.addComponentListener(tf);
		
		frame.pack();
		frame.setVisible(true);
		LOGGER.info("Panel created");
		
		
	}
	private void connect() {
		try {
			ClientIO.setSocket(new Socket(HOST, PORT));
		} catch (final UnknownHostException e) {
			LOGGER.warning(e.getMessage());
		} catch (final IOException e) {
			LOGGER.warning(e.getMessage());
		}
	}
	private void setClient(Integer id) {
		iD=id;
		
		
	}
	public class TabFocus implements FocusListener, ActionListener, ComponentListener,HierarchyListener{
		@Override
		public void focusGained(FocusEvent arg0) {
			// TODO Auto-generated method stub
			//l.setVisible(false);
			//td2.setVisible(true);
			System.out.println("Working");
			
			
		}

		@Override
		public void focusLost(FocusEvent arg0) {
			// TODO Auto-generated method stub
			frame.remove(l);
			
		}

		@Override
		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			
				
			
			//frame.remove(l);
			
		}

	

		@Override
		public void componentHidden(ComponentEvent arg0) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void componentMoved(ComponentEvent arg0) {
			// TODO Auto-generated method stub
			//l.setVisible(false);
			//td2.setVisible(true);
			//System.out.println("Working");
			//l.transferFocus();
			//td2.show();
			
		}

		@Override
		public void componentResized(ComponentEvent arg0) {
			// TODO Auto-generated method stub
			
			
		}

		@Override
		public void componentShown(ComponentEvent arg0) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void hierarchyChanged(HierarchyEvent arg0) {
			// TODO Auto-generated method stub
			
		}
		
	}
}

